<?php
defined('IN_YUNYECMSAdmin') or exit('No permission.');
core::load_admin_class('admin');
class category extends YUNYE_admin {
	private $modellist;
	private $lang;  //默认语言
	function __construct() {
		parent::__construct();
		$this->db = core::load_model('category_model');
		$this->modellist=$this->db->select("select * from `#yunyecms_model` where modelname<>'' order by ordernum asc ");
		if(!getroot('column','view')){
			messagebox(Lan('no_permission_columnview'),'back',"warn");			
		 } 
	    $this->lang=getlangid();
	}
	 //加载首页
	  public function init(){
			if(!getroot('column','view')){
					messagebox(Lan('no_permission_columnview'),'back',"warn");			
			 } 		  
		  $parnav='<li><a href=\"'.url_admin('init',"category").'\" target=\"maincontent\">内容</a></li><li><a href=\"'.url_admin('init','category').'\" target=\"maincontent\">栏目管理</a></li><li class=\"active\">栏目列表</li>';
		   if(!getroot('users','logs')){
			  messagebox(Lan('no_permission'),'back',"warn");			
		   }
		 $pagesize=20;
	     if(!empty($_REQUEST['parentid'])&&is_numeric($parentid)){
			  $parentid=intval(usafestr($_REQUEST['parentid']));
		      $where=" where pid={$parentid} and lang={$this->lang} ";
		    } else{
		      $where=" where pid=0 and lang={$this->lang} ";
		  }
		 $sqlquery="select * from `#yunyecms_category`  ";
		 $sqlcnt=" select count(*) from `#yunyecms_category` ";
		 $order=" order by `ordernum` asc , `addtime` desc ";
		  if(isset($_REQUEST)){
		   if(!empty($_REQUEST["searchkey"])){
		        $searchkey=usafestr(trim($_REQUEST["searchkey"]));
		        $where=$where." and ( `title`  like '%{$searchkey}%'  )";
			  }
		 }
		 $pagearr=$this->db->pagelist($sqlcnt,$sqlquery,$where,$order,$pagesize);
		 if($pagearr["count"]!=0){
			 $list=$pagearr["query"];
			 foreach($list as $key=>$var){
				 $list[$key]['pic']=dopic($var['pic']);
			 }
			 $pages=$pagearr["page"];
		 }
		 require tpl_adm('category_list');
	  }
	
    public function add(){
			$lang_list=getalllang();
			$langid=intval($this->lang);
			$nums=count($lang_list);
			$tablename='category';
		    if(!empty($_REQUEST ['pid'])){
				 $strpid=yytrim($_REQUEST["pid"]);
				 if(!is_numeric($strpid)){
				   messagebox("参数错误",url_admin('init'));
				 }
			 foreach($lang_list as $kk=>$vv){
				 $lid=$vv['id'];
				 $ldef=$vv['isdefault'];
				 $lang_list[$kk]['lang_icon']=dopic($vv['lang_icon']);
				 $psyn=$this->db->getfield('syn',$strpid,$tablename);
			     $pcate[$lid]=$this->db->select("select * from `#yunyecms_category` where `syn`= {$psyn} and lang={$lid}");
				 if(empty($pcate[$lid])){
					 // messagebox("该分类的{$vv['title']}父栏目不存在，请先添加！<br/>若您不需要语言版-{$vv['title']},可在语言版管理里面关闭！",url_admin('init'));
					  messagebox("该分类的{$vv['title']}父栏目不存在，请先添加！",url_admin('init'));
				 }
			   }
			 }
		   if(!empty($_GET["id"])){
					    if(!is_numeric($_REQUEST["id"])){
							  messagebox("错误的参数！",url_admin('init'),"error");
						  }
					$parnav='<li><a href=\"'.url_admin('init','category').'\" target=\"maincontent\">内容</a></li><li><a  href=\"'.url_admin('init','category').'\" target=\"maincontent\">栏目管理</a></li><li class=\"active\">修改栏目</li>';
					     $id=intval($_GET["id"]);
			   		     $definfo=$this->db->find("select * from `#yunyecms_category` where `id`= {$id}");
				         if(empty($definfo)){
						     $row=$this->db->find("select * from `#yunyecms_category` where `syn`= {$id} and lang={$langid}");
						 }else{
							 $row=$definfo;
						 }
				         if($row['pic']) $row['pic']=dopic($row['pic']);
						 $synid=$row['syn'];
						 if(!is_numeric($id)||empty($id)){
								   messagebox("栏目参数错误",url_admin('init'));
								 }
				          foreach($lang_list as $kk=>$vv){
							 $lid=$vv['id'];
							 $ldef=$vv['isdefault'];
						     $row_shadow[$lid]=$this->db->find("select * from `#yunyecms_{$tablename}` where `syn`= {$synid} and lang={$lid}");
				             if($row_shadow[$lid]['pic']) $row_shadow[$lid]['pic']=dopic($row_shadow[$lid]['pic']);
							 if($row_shadow[$lid]){
								 $pcate1[$lid]=$this->db->select("select * from `#yunyecms_category` where `id`= {$row_shadow[$lid]["pid"]} and lang={$lid}");
							 }else{
								 if($row['pid']){
									 $row['psyn']=$this->db->getfield('syn',$row['pid'],$tablename);
									 $pcatecheck=$this->db->find("select * from `#yunyecms_{$tablename}` where `syn`= {$row['psyn']} and lang={$lid}");
									 if(empty($pcatecheck)){
									   messagebox("该分类的{$vv['title']}父栏目不存在，请先添加！",url_admin('init'));
									 }else{
										$pcate1[$lid][0]=$pcatecheck;
									 }
								 }
							 }
						  }
					  if(empty($row)){
						   messagebox("栏目不存在",$_SERVER['HTTP_REFERER']);			
					  }
				   $yyact="edit";
			}else{
				 if(!getroot('column','add')){
						messagebox(Lan('no_permission_columnadd'),'back',"warn");			
				 } 
				$yyact=yyact_get("add");
				$parnav='<li><a href=\"'.url_admin('init','category').'\" target=\"maincontent\">内容</a></li><li><a href=\"'.url_admin('init','category').'\" target=\"maincontent\">栏目管理</a></li><li class=\"active\">增加栏目</li>';
				if(!empty($strpid)){
							 $sqlordermax="select max(ordernum) as maxordernum from `#yunyecms_category` where `pid`= {$strpid}";
							 }else{
							 $sqlordermax="select max(ordernum) as maxordernum from `#yunyecms_category` where `pid`= 0";
							 }
						$ordermaxquery=$this->db->find($sqlordermax);
						$ordermax=$ordermaxquery["maxordernum"]+1;
				}
	        if(isset($_POST["yyact"])){
				      $pic=usafepic(revpic(trim($_POST["pic"])));
				      $POST_DATA=yytrim($_POST);
					  $data["modelid"]=$POST_DATA["modelid"];
					  $data["pic"]=$pic;
					  $data["pages"]=$POST_DATA["pages"];
					  $data["ordernum"]=$POST_DATA["ordernum"];
					  $data["tplhome"]=$POST_DATA["tplhome"];
					  $data["tpllist"]=$POST_DATA["tpllist"];
					  $data["tplcontent"]=$POST_DATA["tplcontent"];
					  $data["status"]=1;
		             foreach($lang_list as $kk=>$vv){
						  $lid=$vv['id'];
						  $ldef=$vv['isdefault'];
						  if($ldef==1){
				 	          $data["pid"]=$POST_DATA["pid_{$lid}"];
				 	          $data["title"]=usafestr(trim($POST_DATA["title_{$lid}"]));
					          $data["ftitle"]=$POST_DATA["ftitle_{$lid}"];
							  $data['exlink']=uhtmlspecialchars(trim($_POST["exlink_{$lid}"]));
                              $data["isdisplay"]=$POST_DATA["isdisplay_{$lid}"];
							  $data["isgood"]=$POST_DATA["isgood_{$lid}"];							  
							  $data["isfoot"]=$POST_DATA["isfoot_{$lid}"];	
							  $data["dismode"]=$POST_DATA["dismode_{$lid}"];							  
							  $data['seotitle']=uhtmlspecialchars(trim($POST_DATA["seotitle_{$lid}"]));	
							  $data['keywords']=uhtmlspecialchars(trim($POST_DATA["keywords_{$lid}"]));	
							  $data['description']=uhtmlspecialchars(trim($POST_DATA["description_{$lid}"]));
							  $data['lang']=$lid;
							  
							 if(empty($POST_DATA['catdir'])){
							   core::load_class('pinyin');
							   $zhuanhuan=core::load_class('utf8_chinese');
							   $catdir=get_catdir($data["title"],$zhuanhuan);
							   $cnt=$this->db->GetCount("select count(*) from `#yunyecms_category`   where catdir='{$catdir}'");
							   if($cnt>0){
								  $catdir=$catdir.'_'.make_rand_letter(); 
								  $data['catdir']=$catdir;
							   }else{
								  $data['catdir']=$catdir;
							   }
							 }else{
							  $catdir=usafestr(trim($POST_DATA["catdir"]));
							   if($POST_DATA["yyact"]=="add"){
								   $cnt=$this->db->GetCount("select count(*) from `#yunyecms_category`   where catdir='{$catdir}'");
								   if($cnt>0){
										messagebox("栏目目录已经存在，请重新填写!",$_SERVER['HTTP_REFERER']);		
								   } 
							    } 
								$data['catdir']=$catdir;
							 }							  
						     }else{
		                      $data_shadow[$lid]["pid"]=$POST_DATA["pid_{$lid}"];
				 	          $data_shadow[$lid]["title"]=usafestr(trim($POST_DATA["title_{$lid}"]));
					          $data_shadow[$lid]["ftitle"]=$POST_DATA["ftitle_{$lid}"];
							  $data_shadow[$lid]['exlink']=uhtmlspecialchars(trim($_POST["exlink_{$lid}"]));
                              $data_shadow[$lid]["isdisplay"]=$POST_DATA["isdisplay_{$lid}"];
							  $data_shadow[$lid]["isgood"]=$POST_DATA["isgood_{$lid}"];							  
							  $data_shadow[$lid]["isfoot"]=$POST_DATA["isfoot_{$lid}"];							  
							  $data_shadow[$lid]["dismode"]=$POST_DATA["dismode_{$lid}"];							  
							  $data_shadow[$lid]['seotitle']=uhtmlspecialchars(trim($POST_DATA["seotitle_{$lid}"]));	
							  $data_shadow[$lid]['keywords']=uhtmlspecialchars(trim($POST_DATA["keywords_{$lid}"]));	
							  $data_shadow[$lid]['description']=uhtmlspecialchars(trim($POST_DATA["description_{$lid}"]));
							  $data_shadow[$lid]["modelid"]=$data["modelid"];
							  $data_shadow[$lid]["pic"]=$pic;
							  $data_shadow[$lid]["pages"]=$data["pages"];
							  $data_shadow[$lid]["ordernum"]=$data["ordernum"];
							  $data_shadow[$lid]["tplhome"]=$data["tplhome"];
							  $data_shadow[$lid]["tpllist"]=$data["tpllist"];
							  $data_shadow[$lid]["tplcontent"]=$data["tplcontent"];
							  $data_shadow[$lid]['lang']=$lid;
							  $data_shadow[$lid]['status']=1;
							  $data_shadow[$lid]["catdir"]=$data["catdir"];
							  if(empty($data_shadow[$lid]["title"])){
									messagebox("{$vv['title']}栏目标题不能为空，谢谢!",$_SERVER['HTTP_REFERER']);		
							   }
						  }
					   }				
					   if(empty($data["title"])){
							messagebox("栏目标题不能为空，谢谢!",$_SERVER['HTTP_REFERER']);		
					   }
					   if(empty($data["modelid"])){
							messagebox("模型不能为空，请重新选择!",$_SERVER['HTTP_REFERER']);		
					   }
					   if(!is_numeric($data["modelid"])){
							messagebox("模型参数错误，请重新选择!",$_SERVER['HTTP_REFERER']);		
						 }
			    if($_POST["yyact"]=="add"){
					  $data["addtime"]=time();
					  $data["updatetime"]=time();
				 	  $data["number"]=create_number('category',$this->lang);
					  $insertid=$this->db->insert($data,'category',true);
					  if($insertid){
							   //同步新增其他语言版记录
						        $syndata['syn']=$insertid;
						        $retsyn=$this->db->update($syndata,array('id'=>$insertid));
						        if($retsyn){
									  foreach($lang_list as $kk=>$vv){
										  $lid=$vv['id'];
										  $ldef=$vv['isdefault'];
										  $data_shadow[$lid]['syn']=$insertid;
										  $data_shadow[$lid]["addtime"]=$data["addtime"];
										  $data["updatetime"]=$data["updatetime"];
				 	                      $data_shadow[$lid]["number"]=$data["number"];
										  if($ldef!=1){
										     $retsynadd[$lid]=$this->db->insert($data_shadow[$lid],$tablename,true);
										  }
									  }
									 //$this->db->Autocommit_commit(); 
								}else{
									 $this->db->Autocommit_rollback(); 
								}						 
								$doing="添加栏目—".$data["title"];
								$yyact="addcategory";
								insert_admlogs($doing,$yyact);
								messagebox("添加栏目成功！",url_admin('init'),"success");
					 }else{
								messagebox("添加栏目失败！",url_admin('init'),"error");
					 }
			  }
		      if($_POST["yyact"]=="edit"){
					  $data["updatetime"]=time();
				  	 if(!getroot('column','edit')){
							messagebox(Lan('no_permission_columnedit'),'back',"warn");			
					  } 
					   $id=$_POST["id"];
					   if(!$this->check_exist($id)){
							messagebox("该内容不存在！",url_admin('init'),"warn");
					   }
					   $crow=$this->db->find("select * from `#yunyecms_category` where `id`= {$id}");
				       if(!empty($_POST['catdir'])){
							$catdir=usafestr(trim($_POST["catdir"]));
						    if($catdir!=$crow['catdir']){
								  $cnt=$this->db->GetCount("select count(*) from `#yunyecms_category`   where catdir='{$catdir}'");
								   if($cnt>0){
										messagebox("栏目目录已经存在，请重新填写!",$_SERVER['HTTP_REFERER']);		
								   }
							}
					   }
					   $retres=$this->db->update($data,"id={$id}");
						if($retres){
									  //同步更新其他语言版
							     	  foreach($lang_list as $kk=>$vv){
										  $lid=$vv['id'];
										  $ldef=$vv['isdefault'];
										  $rs_check=$this->db->GetCount("select count(*) from `#yunyecms_{$tablename}` where `syn`= {$id} and lang={$lid}");
										  if($rs_check){
										     $data_shadow[$lid]["updatetime"]=$data["updatetime"];
											 $retsynadd[$lid]=$this->db->update($data_shadow[$lid],array("syn"=>$id,"lang"=>$lid));  
										  }else{
										     $data_shadow[$lid]['syn']=$crow['syn'];
										     $data_shadow[$lid]['number']=create_number('category',$this->lang);
										     $retsynadd[$lid]=$this->db->insert($data_shadow[$lid],$tablename,true);
										  }
									  } 							
							
									$doing="更新栏目—".$data["title"];
									$yyact="updatecategory";
									insert_admlogs($doing,$yyact);
									messagebox("栏目更新成功！",url_admin('init'),"success");
						 }else{
									messagebox("栏目更新失败！",url_admin('init'),"error");
						 }
			  }			  
		  }
		require tpl_adm('category_add');
	 }	
	  

    public function finaldelete() {
			 if(!getroot('column','del')){
					messagebox(Lan('no_permission_columndel'),'back',"warn");			
			  } 
            $id = $_REQUEST["id"];
		    if(!is_array($id)){
			  $id=compact('id');
			}
			$idarray=$id;
			foreach($idarray as $key=>$var){
				        if(!is_numeric($var)){
						  messagebox("错误的参数！",url_admin('init'),"error");
					    }
                        $var = usafestr($var);
		                $curcategory=$this->db->find("select id,modelid,pic,syn from `#yunyecms_category` where `id`= {$var}");
						if($curcategory){
                          $mid=$curcategory["modelid"];
                          $picfile=$curcategory["pic"];
                          $syn=$curcategory["syn"];
							 if(!empty($picfile)){
								 file_delete($picfile);
							 }
						    $modname=getmodel($mid);
						    $tablename=$modname['tablename'];
						    $modeltype=$modname['modeltype'];
						    $tablename="m_".$tablename;
						    if(!empty($tablename)){
								  if($modeltype!=3){
		                          $cur_ct=$this->db->select("select * from `#yunyecms_{$tablename}` where `catid`= {$var}");
								  if($cur_ct){
									  foreach($cur_ct as $key2=>$var2){
										  $ct_thumb=$var2['pic'];
										  if(!empty($var2["content"])){
											  $ct_content_img=getcontentimg($var2['content']);
											  $ct_content_img=uhtmlspecialchars_decode($ct_content_img);
												  if(!empty($ct_thumb)){
														 file_delete($ct_thumb);
												   }
												  foreach($ct_content_img as $key3=>$var3){
														 file_delete($var3);
												  }
											  }
									    }
								   }
								}
								$re = $this->db->delete("catid={$syn}",$tablename);
						   }
							
							//同步删除首页模块及内容
							$homeset_syn=$this->db->getfield("syn",$var,'homeset','catid');
							if($homeset_syn) $retres =$this->db->delete("syn = {$homeset_syn}","homeset");
							$syncat=$this->db->select("select id from `#yunyecms_category` where `syn`='{$syn}'");
							foreach($syncat as $scat){
								 $subcatsyn=get_cat_child($scat['id']);
								 $catidstr=implode(',', $subcatsyn);
								 $retres2 =$this->db->delete(" id in ($catidstr) ","category");	
								 $re3 = $this->db->delete("catid in ($catidstr) ",$tablename);
								 $re4 = $this->db->delete("catid in ($catidstr) ","homeset");
							 }
							$retres2 =$this->db->delete("syn = {$syn}","category");	
						}
			
					}
            if(isset($idarray)) { 
                if ($retres !== false) {
				    messagebox(Lan('admin_delete_success'),url_admin('init','category'),"success");
                } else {
				    messagebox(Lan('admin_delete_error'),url_admin('init','category'),"warn");
                }
             } else {
				   messagebox(Lan('admin_delall_lessone'),url_admin('init','category'),"warn");
            }
    }	
	
		
    public function check(){
		 if(!getroot('column','edit')){
			  messagebox(Lan('no_permission_columnedit'),'back',"warn");			
		  } 
        parent::infocheck("category",$this->db);
    }	
	
    public function nocheck() {
		 if(!getroot('column','edit')){
			messagebox(Lan('no_permission_columnedit'),'back',"warn");			
		 } 
        parent::infonocheck("category",$this->db);
    }		
	 
	private function check_exist($id) {
		 $id = trim($id);
		 if(empty($id)){
		     return false;
			 }else{
			    if(!is_numeric($id)){
					  return false;
				 }
			  if ($this->db->find("select count(*) as cnt from `#yunyecms_category` where `id`= {$id}")){
				  return true;
			  }				 
		  }
	  }	

	 
}
?>
